<?php
require_once('uml_common.php');

function registerUser($user, $pass1, $pass2) {
  $errorText = '';
  if($pass1 != $pass2) $errorText = 'Passwords are not identical.';
  elseif(strlen($pass1) < 6) $errorText = 'Password is too short.';
  elseif('' != getPassword($user)) $errorText = "The selected user name is taken!";
  
  if ($errorText == '') {
    $sql = 'INSERT INTO users(user, password) VALUES(:user, :pass)';
    try {
      $dbh = new PDO('sqlite:./uml.db', null, null);
      $sth = $dbh->prepare($sql);
      $sth->execute(array(':user' => $user, ':pass' => md5($pass1)));
    }
    catch (Exception $e) {
      die("<p>Database error!</p>");
    }
  }
  return $errorText;
}

if (isset($_POST['submitBtn'])){
  $username  = isset($_POST['username']) ? $_POST['username'] : '';
  $password1 = isset($_POST['password1']) ? $_POST['password1'] : '';
  $password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
  $error = registerUser($username, $password1, $password2);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>Register User</title>
  <link href="uml_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="uml_main">
    <?php if((!isset($_POST['submitBtn'])) || ($error != '')) {?>
      <div class="uml_caption">Register user</div>
        <form class="uml_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="registerform">
          <table width="100%">
            <tr><td>Username:</td><td> <input class="uml_input" name="username" type="text"  /></td></tr>
            <tr><td>Password:</td><td> <input class="uml_input" name="password1" type="password" /></td></tr>
            <tr><td>Confirm password:</td><td> <input class="uml_input" name="password2" type="password" /></td></tr>
            <tr><td colspan="2" align="center"><input class="uml_submit" type="submit" name="submitBtn" value="Register" /></td></tr>
          </table>  
        </form>

    <?php 
    }
    if (isset($_POST['submitBtn'])){
    ?>
      <div class="uml_caption">Registration result:</div>
      <div class="uml_result">
        <table width="100%"><tr><td><br/>
    <?php
      if ($error == '') {
        echo " User: $username was registered successfully!<br/><br/>";
        echo ' <a href="uml_login.php">You can login here</a>';
      }
      else echo $error;
    ?>
          <br/><br/></td></tr>
        </table>
      </div>
    <?php
    }
    ?>
  </div>
</body>
</html>
